"""
通用过滤器模型
支持多种数据类型的条件查询过滤
"""

from typing import Optional, List, Dict, Any, Union
from datetime import datetime, date
from enum import Enum
from pydantic import BaseModel, Field
import uuid


class Operator(str, Enum):
    """查询操作符枚举"""
    EQUALS = "equals"
    NOT_EQUALS = "not_equals"
    GREATER_THAN = "greater_than"
    GREATER_THAN_OR_EQUAL = "greater_than_or_equal"
    LESS_THAN = "less_than"
    LESS_THAN_OR_EQUAL = "less_than_or_equal"
    IN = "in"
    NOT_IN = "not_in"
    LIKE = "like"
    ILIKE = "ilike"
    IS_NULL = "is_null"
    IS_NOT_NULL = "is_not_null"
    BETWEEN = "between"
    CONTAINS = "contains"  # 用于数组或JSON字段


class SortOrder(str, Enum):
    """排序顺序枚举"""
    ASC = "asc"
    DESC = "desc"


class Condition(BaseModel):
    """单个条件模型"""
    field: str = Field(..., description="字段名")
    operator: Operator = Field(..., description="操作符")
    value: Optional[Any] = Field(None, description="值（对于is_null/is_not_null可为空）")


class LogicalOperator(str, Enum):
    """逻辑操作符枚举"""
    AND = "and"
    OR = "or"


class FilterGroup(BaseModel):
    """过滤器组（支持嵌套逻辑）"""
    operator: LogicalOperator = Field(LogicalOperator.AND, description="组内逻辑操作符")
    conditions: List[Union['Condition', 'FilterGroup']] = Field(..., description="条件列表")


class SortField(BaseModel):
    """排序字段模型"""
    field: str = Field(..., description="排序字段名")
    order: SortOrder = Field(SortOrder.ASC, description="排序顺序")


class GenericFilter(BaseModel):
    """通用过滤器模型"""
    conditions: Optional[List[Union[Condition, FilterGroup]]] = Field(
        None, description="过滤条件列表"
    )
    search: Optional[str] = Field(None, description="全文搜索关键词")
    search_fields: Optional[List[str]] = Field(None, description="搜索字段列表")
    sort_by: Optional[List[SortField]] = Field(None, description="排序字段列表")
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页大小")
    include_total: bool = Field(True, description="是否包含总数统计")


class QueryResponse(BaseModel):
    """查询响应模型"""
    data: List[Dict[str, Any]] = Field(..., description="查询结果数据")
    total: Optional[int] = Field(None, description="总记录数")
    page: int = Field(..., description="当前页码")
    page_size: int = Field(..., description="每页大小")
    total_pages: Optional[int] = Field(None, description="总页数")


class ColumnQueryInfo(BaseModel):
    """列查询信息"""
    name: str = Field(..., description="列名")
    type: str = Field(..., description="数据类型")
    nullable: bool = Field(..., description="是否可为空")


class TableQueryInfo(BaseModel):
    """表查询信息"""
    table_name: str = Field(..., description="表名")
    columns: List[ColumnQueryInfo] = Field(..., description="列信息列表")
    primary_keys: List[str] = Field(default_factory=list, description="主键列列表")


# 更新ForwardRefs
Condition.model_rebuild()
FilterGroup.model_rebuild()
GenericFilter.model_rebuild()
